import { FC, useCallback, useState } from 'react';
import { Upload, message } from 'antd';
import { observer } from 'mobx-react';
import FilesCrop from 'rb-files-crop';

import Button from '../Button';
import Icons from '../Icons';
import styles from './index.module.less';

import { API_HOST, PROXY_API, getAccessToken } from '@/utils/config';

import type { UploadChangeParam, UploadFile, UploadProps } from 'antd/lib/upload/interface';

export type AvatarUploadProps = {
  /** 已上传头像的url */
  value?: string;

  /** 上传头像成功后触发事件 返回上传成功后头像的url */
  onChange?: (url: string) => void;
};

const AvatarUpload: FC<AvatarUploadProps> = ({ value, onChange }) => {
  const [imageLoading, setImageLoading] = useState<boolean>(false);
  const [imageUrl, setImageUrl] = useState<string>(value || '');
  const [messageApi, contextHolder] = message.useMessage();
  const messageKey = 'image-message';

  /** 图标上传 */
  const handleChange: UploadProps['onChange'] = useCallback(
    (info: UploadChangeParam<UploadFile>) => {
      console.log(info);

      // 启用loading
      if (info.file.status === 'uploading') {
        setImageLoading(true);
        messageApi.open({
          key: messageKey,
          type: 'loading',
          content: '上传中...'
        });
        return;
      }

      // 报错提示
      if (info.file.status === 'error') {
        let tipInfo = '上传失败';
        // 报错信息
        if (info.file.response && !info.file.response.success && info.file.response.message) {
          tipInfo = `${tipInfo}: ${info.file.response.message}`;
        }
        setImageLoading(false);
        messageApi.open({
          key: messageKey,
          type: 'error',
          content: tipInfo
        });
      }

      // 上传成功
      if (info.file.status === 'done') {
        setImageLoading(false);
        // 设置上传成功的图片url
        if (
          info.file.response &&
          info.file.response.success &&
          info.file.response.data &&
          info.file.response.data.filePath
        ) {
          setImageUrl(info.file.response.data.filePath);
          onChange?.(info.file.response.data.filePath);
        }
        messageApi.open({
          key: messageKey,
          type: 'success',
          content: '上传成功'
        });
      }
    },
    [onChange]
  );

  return (
    <div className={styles.rbAvatarUpload}>
      {contextHolder}
      <FilesCrop>
        <Upload
          action={`${API_HOST}${PROXY_API}/develop/file/upload`}
          headers={{
            Authorization: getAccessToken()
          }}
          accept="image/*"
          listType="picture"
          showUploadList={false}
          maxCount={1}
          onChange={handleChange}
        >
          {(imageUrl || value) && (
            <img src={imageUrl || value} alt="avatar" className={styles.image} />
          )}
          <Button loading={imageLoading} icon={<Icons type="UploadOutlined" />}>
            上传
          </Button>
        </Upload>
      </FilesCrop>
    </div>
  );
};

export default observer(AvatarUpload);
